package com.cssl.websocket;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/echo/{userno}")
public class EchoSocket {
	System.out.println("########iii#####");
	private static int onlineCount=0; //当前在线人数
	//concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    private static ConcurrentHashMap<String, EchoSocket> webSocketSet = new ConcurrentHashMap<String, EchoSocket>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //当前发消息的人员编号
    private String userno = "";

	
    //连接成功的方法
	@OnOpen
	public void open(@PathParam("userno") String userno,Session session,EndpointConfig config) {
		System.out.println(session.getId()+"#############");
		this.userno=userno;
		this.session=session;
		webSocketSet.put(userno, this);
		addOnlineCount();
        System.out.println(userno+"有新连接加入！当前在线人数为" + getOnlineCount());
	}
	@OnClose
	public void close(Session session,CloseReason reason){
		System.out.println(userno + "连接关闭了");
		webSocketSet.remove(userno);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());   
	}
	
	/**
     * 接收到客户端的信息
     * @param msg
     * @param last
     */
    @OnMessage
    public void message(Session session,boolean last,String message){
    	String sendUserno = message.split("[|]")[1];
        String sendMessage = message.split("[|]")[0];
        String now = getNowTime();
        try {
        	if (webSocketSet.get(sendUserno) != null) {
        		System.out.println(now + "用户" + userno + "发来消息：" + " <br/> " + sendMessage);
                webSocketSet.get(sendUserno).sendMessage(sendMessage);
            } else {
            	System.out.println("当前用户不在线");
            	 webSocketSet.get(userno).sendMessage("当前用户不在线");
            }

           // session.getBasicRemote().sendText("ni hao too");
           // Thread.sleep(3000);//三秒后再发送一条信息，用于验证是否实现数据实时更新
           // session.getBasicRemote().sendText("ni hao too twice");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private String getNowTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
        
    }

    /**
    *错误监听（当没有关闭socket连接就关闭浏览器会异常）
    */

     @OnError
     public void error(Session session, Throwable error){
          String id = session.getId();
          System.out.println("出错的session的id是" + id);
     }

     public EchoSocket(){
       System.out.println("Socket对象创建");
       //通过对象的创建可以知道不同socket之间的通信不会共享成员变量
     }
     
     /**
      * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
      *
      * @param message
      * @throws IOException
      */
     public void sendMessage(String message) throws IOException {
         this.session.getBasicRemote().sendText(message);
         //this.session.getAsyncRemote().sendText(message);
     }
  
     public static synchronized int getOnlineCount() {
         return onlineCount;
     }
  
     public static synchronized void addOnlineCount() {
    	 EchoSocket.onlineCount++;
     }
  
     public static synchronized void subOnlineCount() {
    	 EchoSocket.onlineCount--;
     }

}
